import { BaseContext } from "koa";
import {Exception} from "../utils/exception";
import { auth as Auth } from "../utils/auth";
const authorize = () => {
  return (context: any, key: string, desc: PropertyDescriptor) => {
    context[key].authorize = async (ctx: BaseContext, next: any) => {
      try {
        let token = ctx.request.headers["authorization"];
        // token = token.replace("Bearer ", "");
        token = token && token.replace("Bearer", "").trim();
        if (token) {
          let payload: any = await Auth.verifyToken(token);
          const { time, timeout } = payload;
          let data = new Date().getTime();
          if (data - time <= timeout) {
            ctx.state.user = payload;
            return next();
          }
          return ctx.body = Exception(110, '登录已过期，请重新登录');
        }
        return ctx.body = Exception(110, '请先登录');
      } catch (err) {
        console.log(err);
        return ctx.body = Exception(110, '请先登录');
      }
    };
  };
};

export default authorize;
